package com.inplaceedit.client.ui;

import java.util.Iterator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiChild;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.HasOneWidget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.core.gwt.ui.client.IsFocusable;

public class InPlaceDialogPanel extends Composite implements HasWidgets {

	interface Binder extends UiBinder<Widget, InPlaceDialogPanel> {
	}

	private static Binder uiBinder = GWT.create(Binder.class);

	@UiField
	DeckPanel container;
	@UiField
	SimplePanel commandPanel;
	@UiField
	SaveCancelPanel dialogPanel;

	SaveCancelDialog dialog;

	public InPlaceDialogPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		hideDialog();
	}

	@UiChild(limit = 1)
	@Override
	public void add(final Widget w) {
		dialogPanel.add(w);
	}

	public SaveCancelDialog asDialog() {
		if (dialog == null) {
			dialog = SaveCancelDialogAdapter.of(new Command() {
				@Override
				public void execute() {
					showDialog();
				}
			}, new Command() {
				@Override
				public void execute() {
					hideDialog();
				}
			}, getSaveCommand(), getCancelCommand());
		}
		return dialog;
	}

	@Override
	public void clear() {
		dialogPanel.clear();
	}

	public HasClickHandlers getCancelCommand() {
		return dialogPanel.getCancelCommand();
	}

	public HasOneWidget getCommandPanel() {
		return commandPanel;
	}

	public HasOneWidget getContentPanel() {
		return dialogPanel.getContentPanel();
	}

	public HasOneWidget getDialogPanel() {
		return dialogPanel.getContentPanel();
	}

	public HasClickHandlers getSaveCommand() {
		return dialogPanel.getSaveCommand();
	}

	public void hideDialog() {
		container.showWidget(0);
	}

	@Override
	public Iterator<Widget> iterator() {
		return dialogPanel.iterator();
	}

	@Override
	public boolean remove(final Widget w) {
		return dialogPanel.remove(w);
	}

	@UiChild(limit = 1, tagname = "command")
	public void setCommandWidget(final Widget w) {
		commandPanel.setWidget(w);
	}

	public void showDialog() {
		container.showWidget(1);
		final Widget w = dialogPanel.getContentPanel().getWidget();
		if (w != null) {
			if (w instanceof Focusable) {
				((Focusable) w).setFocus(true);
			} else if (w instanceof IsFocusable) {
				final Focusable f = ((IsFocusable) w).asFocusable();
				if (f != null) {
					f.setFocus(true);
				}
			}
		}
	}
}
